package com.qf.swagger2204.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Slf4j
@Configuration
public class QueryFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String url = httpRequest.getRequestURI();
        long startTime = System.currentTimeMillis();
        boolean var20 = false;

        // 此方式支持form-data传参方式参数获取，其他传参方式请自行研究
        Map<String, String[]> parameterMap = httpRequest.getParameterMap();
        List<String> parameterList = new ArrayList<>();
        parameterMap.forEach((key, value) -> {
            parameterList.add(key + ":" + Arrays.toString(value));
        });

        try {
            var20 = true;
            chain.doFilter(request, response);
            var20 = false;
        } finally {
            if (var20) {
                long var14 = System.currentTimeMillis();
                long time = var14 - startTime;
                String clientIp = httpRequest.getHeader("x-forwarded-for");
                if (clientIp == null) {
                    clientIp = httpRequest.getRemoteAddr();
                }

                log.info("客户端IP：" + clientIp + "" + ", 请求地址：" + url + ", 请求参数：{" + String.join(",", parameterList) + "}, 响应时间：" + time + "ms");
            }
        }

        long timeConsuming = System.currentTimeMillis() - startTime;
        String clientIp = httpRequest.getHeader("x-forwarded-for");
        if (clientIp == null) {
            clientIp = httpRequest.getRemoteAddr();
        }

        log.info("客户端IP：" + clientIp + "" + ", 请求地址：" + url + ", 请求参数：{" + String.join(",", parameterList) + "}, 响应时间：" + timeConsuming + "ms");
    }
}
